<?php


namespace App\Admin\Controllers;


use App\Models\Settings;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;

class UploadConfigController extends AdminController
{
    public function index(Content $content)
    {
        return $content->body($this->form());
    }

    protected function form()
    {
        $form = new Form();

        $form->action(admin_route('upload_config.store'));
        $form->title('上传配置');

        $config = config('filesystems');
        $driver = $config['default'] == 'local' ? 'local' : 'ali_oss';
        $oss = $config['disks']['oss'];

        $form
            ->select('driver', '存储方式')
            ->options(['local' => '本地存储', 'ali_oss' => '阿里云oss'])
            ->value($config['upload_driver'] ?? $driver)
            ->when('ali_oss', function (Form $form) use ($oss) {
                $oss = Settings::where('group', '=', 'upload')->pluck('value', 'name')->all();
                $form->text('ali_access_key', '公钥信息')->required()->value($oss['ali_access_key'] ?? '')->help('Your Aliyun OSS AccessKeyId');
                $form->text('ali_secret_key', '私钥信息')->required()->value($oss['ali_secret_key'] ?? '')->help('Your Aliyun OSS AccessKeySecret');
                $form->text('ali_oss_domain', '访问域名')->required()->value($oss['ali_oss_domain'] ?? '')->help('Your Aliyun OSS DOMAIN');
                $form->text('ali_endpoint', '数据中心')->required()->value($oss['ali_endpoint'] ?? '')->help('OSS endpoint');
                $form->text('ali_bucket', '空间名称')->required()->value($oss['ali_bucket'] ?? '')->help('OSS bucket name');
                $form->text('ali_root', '上传根目录')->value($oss['ali_root'] ?? '');
            });


        $form->disableListButton();
        $form->disableResetButton();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();

        return $form;
    }

    public function store()
    {
        // 目前只用阿里云oss

        $data = request()->only([
            'driver', 'ali_access_key', 'ali_secret_key', 'ali_endpoint', 'ali_bucket', 'ali_root', 'ali_oss_domain'
        ]);

        try {
            DB::beginTransaction();

            foreach ($data as $key => $item) {
                Settings::updateOrCreate(
                    ['group' => 'upload', 'name' => $key],
                    ['value' => $item]
                );
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            log_exception('保存上传配置失败', $e);
            return JsonResponse::make()->error('保存失败');
        }

        return JsonResponse::make()->success('保存成功！')->refresh();
    }
}
